package main

import (
	"fmt"
	"net"
)

func process(conn net.Conn) {
	defer conn.Close()
	// 读取 conn 的数据
	buf := [128]byte{}
	// n 为读取的长度
	n, err := conn.Read(buf[:])
	if err != nil {
		fmt.Printf("conn read error: %s", err)
		return
	}

	fmt.Printf("读取到的数据内容：%s", string(buf[:n]))
}

func main() {
	listen, err := net.ListenUDP("udp", &net.UDPAddr{
		IP:   net.IPv4(0, 0, 0, 0),
		Port: 3000,
	})
	if err != nil {
		fmt.Println("error is err:", err)
		return
	}
	defer listen.Close()
	// 循环读取
	for {
		var data [1024]byte
		n, addr, err := listen.ReadFromUDP(data[:])
		if err != nil {
			fmt.Println("read udp failed, error:", err.Error())
			return
		}
		fmt.Printf("data: %v addr: %v count:%v \n", string(data[:n]), addr, n)
		_, err = listen.WriteToUDP([]byte("我都到的数据是:"+string(data[:n])), addr) // 发送数据
		if err != nil {
			fmt.Println("write to udp failed, err:", err)
			continue
		}
	}
}
